package com.ykt.controller;

import com.jfinal.ext.route.ControllerBind;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.ykt.common.utils.ExcelExportUtil;
import com.ykt.common.utils.ExcelExportUtil.Pair;
import com.ykt.model.Admin;
import com.ykt.model.Order;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;

@ControllerBind(controllerKey="/order")
public class OrderController extends BaseController<Order> {

	public OrderController() {
		super(Order.class);
	}
	
	@Override
	public void grid() {
        int page = getParaToInt("page", 1);
        int rows = getParaToInt("rows", 20);
//        String shopIds = getPara("sids");
        
        Admin admin = getCurrentUser();
        Map<String, String> params = this.toParaMap();
        if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
        	params.put("EQ_o.shop_id",admin.getInt(Admin.shopId).toString());
        }
        
        try {
            Page<Order> date = Order.dao.pageFindModel(page, rows, params);
            rendDataGrid(date);
        } catch (Exception e) {
            log.error(e);
            rendJson(false, e.getMessage());
        }
    }
	
//	@Override
//	public void index() {
//		setAttr("hasAudit",hasPerm("/order/audit"));
//		setAttr("hasCopy",hasPerm("/order/copy"));
//	}
	
	/**
	 * 修改订单状态
	 */
	public void audit() {
		String msg = "状态已变更";
		try {
			Order order = Order.dao.findById(getParaToInt(0));
			if(isParaExists(1)){
				order.set("status", getPara(1));
			}else{
				String status = order.getStr("status");
				order.set("status", status);
			}
			order.update();
			int id = order.getInt("id");
			rendJson(true, msg, id, new Random().nextLong());
		} catch (Exception e) {
			log.error("保存异常", e);
			rendJson(false, "保存异常！");
			e.printStackTrace();
		}
	}
	
	/**
	 * 批量修改订单状态，发货等
	 */
	public void batchOperator() {
		try {
			String ids = this.getPara("ids");
			String status = this.getPara("status");
			String msg = "批量操作成功！";
			
			boolean flag = true;
			
			if(status.equals("USER_UNRECEIPT")){
				List<Order> olist = Order.dao.find("select id from `order` where id in (" + ids + ") and `status`!='MERCHANT_UNDELIVERY' ");
				if(olist.size() > 0){
					flag = false;
					
					msg = "所选数据含非发货订单！";
					rendJson(false, msg);
				}
			}
			if(flag){
				Db.update("update `order` o set o.updated_time=NOW(), o.`status`='"+status+"' where o.id in (" + ids + ")");
				rendJson(true, msg);
			}

		} catch (Exception e) {
			log.error("批量操作异常", e);
			rendJson(false, "操作异常！");
		}
	}
	
	/**
	 * 订单导出excel报表
	 */
	public void excelExport(){
		
		Admin admin = getCurrentUser();
        Map<String, String> params = this.toParaMap();
        if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
        	params.put("EQ_o.shop_id",admin.getInt(Admin.shopId).toString());
        }

        params.put("NE_o.order_type","PARENT");
        
		List<Order> dataList = Order.dao.findByOrderParam(params);
		Map<String, String> exportCount = Order.dao.findByOrderParamCount(params);
		
//		PoiRender excel = new PoiRender(dataList);
//		String[] columns = {"id","userName","userPhone","shopName","amount","payTime","status","createTime"};
//		String[] heades = {"订单编号","下单用户","用户手机号","商家","交易金额","支付时间","状态","下单时间 "};
//		render(excel.sheetName("订单").headers(heades).columns(columns).fileName("订单列表.xls"));
		
		List<Pair> titles = new ArrayList<Pair>();
		titles.add(new Pair("id", "订单号"));
		titles.add(new Pair("userName", "下单用户"));
		titles.add(new Pair("userPhone", "用户手机号"));
		titles.add(new Pair("community_name", "服务站"));
		titles.add(new Pair("shopName", "商家"));
		titles.add(new Pair("amount", "交易金额"));
		titles.add(new Pair("payAmount", "实付金额"));
		titles.add(new Pair("payTime", "支付时间"));
		titles.add(new Pair("status", "状态"));
		titles.add(new Pair("createTime", "下单时间"));
		
		ExcelExportUtil.exportByRecord(getResponse(), getRequest(), "订单报表", titles , dataList, exportCount);
		renderNull();
	}
	
	/**
	 * 采购excel报表
	 */
	public void exportFurchaseReport(){
		
		Admin admin = getCurrentUser();
        Map<String, String> params = this.toParaMap();
        if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
        	params.put("EQ_o.shop_id",admin.getInt(Admin.shopId).toString());
        }

        params.put("NE_o.order_type","PARENT");
        
		List<Order> dataList = Order.dao.findByParam4Purchase(params);
		
		List<Pair> titles = new ArrayList<Pair>();
		titles.add(new Pair("goods_name", "商品名称"));
		titles.add(new Pair("counts", "数量（斤）"));
		titles.add(new Pair("unitPrice", "单位（元/斤）"));
		titles.add(new Pair("amountSum", "合计（元）"));
		
		ExcelExportUtil.exportByRecord(getResponse(), getRequest(), "采购报表", titles , dataList, null);
		renderNull();
	}
	
	/**
	 * 分拣excel报表
	 */
	public void exportSortingReport(){
		
		Admin admin = getCurrentUser();
        Map<String, String> params = this.toParaMap();
        if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
        	params.put("EQ_o.shop_id",admin.getInt(Admin.shopId).toString());
        }
        
        params.put("NE_o.order_type","PARENT");
        
		List<Order> dataList = Order.dao.findByParamForProductCount(params);
		
		List<Pair> titles = new ArrayList<Pair>();
		titles.add(new Pair("orderId", "订单号"));
		titles.add(new Pair("recName", "收货人姓名"));
		titles.add(new Pair("recPhone", "收货人电话"));
		titles.add(new Pair("recAddress", "收货人地址"));
		titles.add(new Pair("shopName", "供应商"));
		titles.add(new Pair("orderDetails", "订单内容"));
		titles.add(new Pair("payAmount", "实付金额"));
		titles.add(new Pair("createdTime", "下单时间"));
		
		ExcelExportUtil.exportByRecord(getResponse(), getRequest(), "分拣报表", titles , dataList, null);
		renderNull();
	}
	
	/**
	 * 订单商品汇总
	 */
	public void exportProductCountReport(){
		
		Admin admin = getCurrentUser();
        Map<String, String> params = this.toParaMap();
        if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
        	params.put("EQ_o.shop_id",admin.getInt(Admin.shopId).toString());
        }
		
        params.put("NE_o.order_type","PARENT");
        
		List<Order> dataList = Order.dao.findByParamForProductCount(params);
		
		List<Pair> titles = new ArrayList<Pair>();
		titles.add(new Pair("categoryName", "所属分类"));
		titles.add(new Pair("goods_name", "商品名称"));
		//titles.add(new Pair("summary", "描述"));
		titles.add(new Pair("goodsCount", "数量"));
		titles.add(new Pair("goodUnit", "单位"));
		titles.add(new Pair("sale_price", "单价（元）"));
		titles.add(new Pair("shopName", "所属商家"));
		titles.add(new Pair("community_name", "服务站"));
		
		ExcelExportUtil.exportByRecord(getResponse(), getRequest(), "订单商品汇总", titles , dataList, null);
		renderNull();
	}
	
	/**
	 * 订单商品明细
	 */
	public void exportOrderProductDetailReport(){
		
		Admin admin = getCurrentUser();
        Map<String, String> params = this.toParaMap();
        if(admin.get(Admin.role_ids)!=null && admin.getStr(Admin.role_ids).equals("6")){
        	params.put("EQ_o.shop_id",admin.getInt(Admin.shopId).toString());
        }
		
        params.put("NE_o.order_type","PARENT");
        
		List<Order> dataList = Order.dao.findByParamForOrderProductDetail(params);
		
		List<Pair> titles = new ArrayList<Pair>();
		titles.add(new Pair("orderDate", "下单日期"));
		titles.add(new Pair("order_no", "订单编号"));
		titles.add(new Pair("orderStatus", "订单状态"));
		titles.add(new Pair("shopName", "所属商家"));
		titles.add(new Pair("community_name", "服务站"));
		titles.add(new Pair("categoryName", "商品分类"));
		titles.add(new Pair("goods_name", "商品名称"));
		titles.add(new Pair("goodsCount", "数量"));
		titles.add(new Pair("goodUnit", "单位"));
		titles.add(new Pair("sale_price", "单价（元）"));
		
		
		ExcelExportUtil.exportByRecord(getResponse(), getRequest(), "订单商品明细", titles , dataList, null);
		renderNull();
	}
}
